package no.kolstad.movies.controller;

import java.net.BindException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import no.kolstad.movies.dao.LenderDAO;
import no.kolstad.movies.model.Lender;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;


/**
 *  Copyright [2008] Christopher Kolstad
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software distributed under the License 
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License. 
 */

/**
 *
 * @author chriswk
 */
public class EditLenderController extends SimpleFormController {
    private LenderDAO lDao;
    public void setLenderDAO(LenderDAO lDao) {
        this.lDao = lDao;
    }
  
    protected Log log = LogFactory.getLog(this.getClass());
    
    @Override
    protected Object formBackingObject(HttpServletRequest request)
      throws Exception {

    if (log.isInfoEnabled()) {
      log.info("EditLenderController formBackingObject");
    }

    if (request.getParameter("lender_id") != null
        && !"".equals(request.getParameter("lender_id"))) {
      Long id = Long.parseLong(request.getParameter("lender_id"));
      Lender existingLender = lDao.get(id);
      return existingLender;
    }

    return new Lender();
    }
    
    
    public ModelAndView onSubmit(HttpServletRequest request,
      HttpServletResponse response, Object command, BindException errors)
      throws ServletException {
        
      Lender newLender = (Lender) command;
      if(log.isDebugEnabled()) {
          log.debug("Converted command object. Now saving Lender");
      }
      lDao.save(newLender);
      if(log.isDebugEnabled()) {
          log.debug("Saved successfully");
      }
      request.getSession().setAttribute("statusMessage", "User saved");
      return new ModelAndView(new RedirectView(getSuccessView()));
    }
}
